package com.jungle.jedis;

import com.sun.javafx.scene.control.behavior.OptionalBoolean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisOperator {

    private JedisPool jedisPool;

    public JedisOperator(){

    }

    public JedisOperator(JedisPool jedisPool){
        this.jedisPool = jedisPool;
    }

    public byte[] get(final byte[] key) {
        return excute(new JedisExecutor<byte[]>() {
            @Override
            public byte[] doInJedis(Jedis jedis) {
                return jedis.get(key);
            }
        });
    }

    /**
     * 传一个JedisExcutor的子类，模板设计模式?
     * @param executor
     * @param <T>
     * @return
     */
    public <T> T excute(JedisExecutor<T> executor){
            T result = null;
            Jedis jedis = jedisPool.getResource();
            try {
                result = executor.doInJedis(jedis);
            }
            catch (Exception e){
                throw new RuntimeException(e);
            }
            finally {
                if(jedis!=null){
                    jedis.close();
                }
            }
            return result;
    }

    public String set(final byte[] keyBytes, final byte[] valueBytes) {
            return excute(new JedisExecutor<String>() {
                @Override
                public String doInJedis(Jedis jedis) {
                    return jedis.set(keyBytes,valueBytes);
                }
            });
    }

    public String setex(final byte[] key, final int ttl, final byte[] value) {
        return excute(new JedisExecutor<String>() {
            @Override
            public String doInJedis(Jedis jedis) {
                return jedis.setex(key,ttl,value);
            }
        });
    }


    public long del(final byte[] key) {
        return excute(new JedisExecutor<Long>() {
            @Override
            public Long doInJedis(Jedis jedis) {
                return jedis.del(key);
            }
        });
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }
}
